﻿using System;
using System.Diagnostics;
using wpffc.contracts.domaindata;

namespace wpffc.flashcardbox
{
    public class Fill_batch_from_compartment
    {
        public void Process(Tuple<IFlashCardBox, int> boxAndCompartment)
        {
            var box = boxAndCompartment.Item1;
            var compartmentIndex = boxAndCompartment.Item2;
            Trace.TraceInformation("Fill batch from compartment: {0}, batch state: {1}", compartmentIndex, box.Batch.Status);

            if (BatchNeedsRefill(box.Batch))
                while (box.Batch.Status != BatchStatus.Full)
                {
                    if (box.Compartments[compartmentIndex].Status == CompartmentStatus.Empty) break;
                    box.Batch.Enqueue(MapCardToBatchCard(compartmentIndex, box.Compartments[compartmentIndex].Dequeue()));
                }

            if (box.Batch.Status == BatchStatus.Full)
                Full(box);
            else
                ContinueFilling(box);
        }


        internal static bool BatchNeedsRefill(IBatch batch)
        {
            return batch.Status == BatchStatus.Empty || batch.Status == BatchStatus.NeedsRefill;
        }


        internal static BatchCard MapCardToBatchCard(int compartmentIndex, Card card)
        {
            return new BatchCard {CompartmentIndex = compartmentIndex, Card = card};
        }


        public event Action<IFlashCardBox> Full;
        public event Action<IFlashCardBox> ContinueFilling;
    }
}